let obj={};

/* 保存商品 */
obj.saveGoods = function(goodsList){
  window.localStorage.setItem('goodsList', JSON.stringify(goodsList));
};

/* 获取商品 */
obj.getGoodsList = function(){
  return JSON.parse(window.localStorage.getItem('goodsList')) || {};
};

/* 增加商品 */
obj.add = function(goods){
  let goodsList = this.getGoodsList();
  
  // console.log("goodsList:::::",goodsList );
  // console.log("goods:::::",goods );
  if(goodsList[goods.id]){
    // 有则追加
    goodsList[goods.id] += goods.num;
  }else{
    goodsList[goods.id] = goods.num;
  }
  // console.log(goodsList);

  this.saveGoods(goodsList);
}

/* 删除商品 */
obj.delete = function(id){
  // console.log("传入的id：", id);
  let goodsList = this.getGoodsList();
  
  if(goodsList[id]){
    // console.log("存在" + goodsList);
    delete goodsList[id];
    // console.log("删除了：", goodsList[id]);
    // 删除 对应 id 后， 保存
    this.saveGoods(goodsList);
  }
};

/* 获取购物车的总数量 */
obj.getTotalCount = function(){
  let goodsList = this.getGoodsList();
  // console.log("goodList::::::::::::::::::", goodsList);
  let values = Object.values(goodsList);
  // console.log("values:::::", values);
  let sum = 0;
  values.forEach(val=>sum+=val);
  return sum;
}

// 抛出
export default obj;